package com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.ydkj.a37e_mall.Classes.Model.Request.NewProductListReq;
import com.ydkj.a37e_mall.Classes.Model.Response.NewProductListResp;
import com.ydkj.a37e_mall.R;
import com.ydkj.a37e_mall.Resource.Utils.Async_http_get;
import com.ydkj.a37e_mall.Resource.Utils.CommonUtil;
import com.ydkj.a37e_mall.Resource.Utils.Const;
import com.ydkj.a37e_mall.Resource.Utils.GsonImpl;
import com.ydkj.a37e_mall.Resource.Utils.Rsa;
import com.ydkj.a37e_mall.Resource.View.CustomProgressDialog;
import com.ydkj.a37e_mall.Resource.View.StatusBarUtil;

import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;


/**
 * Created by hong on 2016/3/15.
 * <p>
 * 新品上架
 */
public class NewProductShelves extends BaseActivity {

    private Activity mActivity;
    private PullToRefreshGridView gv_new_product;
    private NewProductGridviewAdapter newProductGridviewAdapter;
    private List<NewProductListResp.ResultEntity.DataEntity> newProductInfoList;
    private static final int LOAD = 0;//加载
    private static final int REFRESH = 1;// 刷新
    private static final int MORE = 2;// 更多
    private ImageView img_back;
    private TextView tv_title;//如果从新品上架进来，设为新品上架，从二手良品设二手良品
    private String id;
    private int page;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_product_shelves);
        mActivity = this;
        init();
        GetNewProductList(REFRESH);
//        initWindow();//沉浸式状态栏
    }

    private void initWindow() {
        StatusBarUtil.setColor(mActivity, getResources().getColor(R.color.A000000), 0);
    }

    private void init() {

        if (this.getIntent().getExtras() != null) {
            id = this.getIntent().getExtras().getString("id");
            Log.e("url", "id==" + id);
        }

        img_back = (ImageView) mActivity.findViewById(R.id.img_back);
        tv_title = (TextView) mActivity.findViewById(R.id.tv_title);

        gv_new_product = (PullToRefreshGridView) mActivity.findViewById(R.id.gv_new_product);
        newProductInfoList = new ArrayList<NewProductListResp.ResultEntity.DataEntity>();
        newProductGridviewAdapter = new NewProductGridviewAdapter(newProductInfoList);

        gv_new_product.setAdapter(newProductGridviewAdapter);
        gv_new_product.setOnRefreshListener2(new PullToRefreshBase.OnRefreshListener2<GridView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
                String label = DateUtils.formatDateTime(mActivity.getApplicationContext(), System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
                // Update the LastUpdatedLabel
                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                // Do work to refresh the list here.
                GetNewProductList(REFRESH);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
                String label = DateUtils.formatDateTime(mActivity.getApplicationContext(), System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
                // Update the LastUpdatedLabel
                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                // Do work to refresh the list here.
                GetNewProductList(MORE);
            }
        });

        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private class NewProductGridviewAdapter extends BaseAdapter {
        private List<NewProductListResp.ResultEntity.DataEntity> newProductGridList;

        private NewProductGridviewAdapter(List<NewProductListResp.ResultEntity.DataEntity> search) {
            if (search == null) {
                search = new ArrayList<NewProductListResp.ResultEntity.DataEntity>();
            }
            newProductGridList = search;
        }

        @Override
        public int getCount() {
            return newProductGridList.size();
        }

        @Override
        public NewProductListResp.ResultEntity.DataEntity getItem(int position) {
            return newProductGridList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder vh = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(mActivity).inflate(R.layout.new_product_shelves_listitem, null);
                vh = new ViewHolder();
                vh.tv_save_money = (TextView) convertView.findViewById(R.id.tv_save_money);
                vh.tv_brand_name = (TextView) convertView.findViewById(R.id.tv_brand_name);
                vh.tv_describe = (TextView) convertView.findViewById(R.id.tv_describe);
                vh.tv_original_price = (TextView) convertView.findViewById(R.id.tv_original_price);
                vh.tv_discount_price = (TextView) convertView.findViewById(R.id.tv_discount_price);
                vh.tv_payment_number = (TextView) convertView.findViewById(R.id.tv_payment_number);
                vh.img_product = (ImageView) convertView.findViewById(R.id.img_product);

            } else {
                vh = (ViewHolder) convertView.getTag();
            }
            convertView.setTag(vh);
            convertView.setClickable(true);

            vh.tv_original_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中划线
            vh.tv_brand_name.setText(getItem(position).getName());
            if (Double.parseDouble(getItem(position).getMarket_price()) == Double.parseDouble(getItem(position).getPrice())) {
                vh.tv_save_money.setVisibility(View.INVISIBLE);
                vh.tv_original_price.setVisibility(View.INVISIBLE);
            } else {
                final double price = Double.parseDouble(getItem(position).getMarket_price()) - Double.parseDouble(getItem(position).getPrice());
                DecimalFormat df = new DecimalFormat("###.00");
                final String price1 = df.format(price);
                vh.tv_save_money.setText("省" + price1 + "元");
                vh.tv_original_price.setText("¥" + getItem(position).getMarket_price());
            }
            vh.tv_describe.setText(getItem(position).getDescription());
            vh.tv_discount_price.setText("¥" + getItem(position).getPrice());
            vh.tv_payment_number.setText(getItem(position).getSales() + "人付款");
//            vh.tv_yuanjia.setText("¥" + getItem(position).getMarket_price());
            ImageLoader.getInstance().displayImage(getItem(position).getList_thumb(), vh.img_product);

            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(NewProductShelves.this, ProductDetails.class);
                    intent.putExtra("id", getItem(position).getId());
                    startActivity(intent);
                }
            });

            return convertView;
        }

        private class ViewHolder {
            public TextView tv_save_money;
            private ImageView img_product;
            public TextView tv_brand_name;
            public TextView tv_describe;
            private TextView tv_original_price;
            public TextView tv_discount_price;
            private TextView tv_payment_number;
        }
    }

    private void GetNewProductList(final int type) {
        CustomProgressDialog.createDialog(mActivity).Show();
        NewProductListReq req = new NewProductListReq();
        if (type == LOAD || type == REFRESH) {
            page = 1;
        } else {
            page = newProductInfoList.size() / 10 + 1;
        }
        req.setActivity_type(id + "");
        req.setPage(page + "");
        req.setPage_size("10");
        req.setOrder("id");
        req.setSort("desc");
        RequestParams params = new RequestParams();
        try {
            String source = req.getString();
            Log.e("ssss", "source==>" + source);

            Rsa rsa = new Rsa();
            secret = rsa.encryptByPublic(source);
        } catch (Exception e) {
            e.printStackTrace();
        }
        params.put("secret", secret);
        Log.e("url", "params==" + params);
        String url = Const.COMMON_ADDRESS + req.urlString();
        Async_http_get.get(url, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                Log.e("url", "newProductList_json==" + response);
                gv_new_product.onRefreshComplete();
                CustomProgressDialog.Dismiss();
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                if (errno.equals("000")) {
                    NewProductListResp resp = GsonImpl.get().toObject(response.toString(), NewProductListResp.class);
                    if (type == LOAD || type == REFRESH) {
                        newProductInfoList.clear();
                        newProductInfoList.addAll(resp.getResult().getData());
                    } else {
                        newProductInfoList.addAll(resp.getResult().getData());
                    }
                    if (newProductInfoList.size() % 10 > 0) {
                        gv_new_product.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                    } else {
                        gv_new_product.setMode(PullToRefreshBase.Mode.BOTH);
                    }
                    newProductGridviewAdapter.notifyDataSetChanged();
                } else {
                    CommonUtil.showToast(mActivity, errmsg);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                gv_new_product.onRefreshComplete();
                CommonUtil.showToast(mActivity, "网络连接失败");
            }
        });
    }
}
